package com.feihong.yw189.activity.buka;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.activity.dingdan.DingDanDetailsActivity;
import com.feihong.yw189.activity.kaika.KaikaUploadPicActivity;
import com.feihong.yw189.activity.kuandai.HengXiangSign;
import com.feihong.yw189.activity.tiaoxingma.TiaoXingMaActivity;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.activity.SearchBlueActivity;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.DingDan.BuKaMoneyModel;
import com.feihong.yw189.model.buka.BuKaDuibiInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 补卡页面   主页
 */

public class BukaActivity extends BaseActivity {


    @BindView(R.id.rl_goback)
    RelativeLayout ivBack;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    @BindView(R.id.rl_saomiao)
    RelativeLayout rlSaoMiao;
    @BindView(R.id.ll_bukapic)
    LinearLayout llTakePic;
    @BindView(R.id.rl_loadtake)
    RelativeLayout rl_loadpic;
    @BindView(R.id.iv_querynumber)
    ImageView mQueryNumber;
    @BindView(R.id.et_bukanumber)
    EditText etbuKaNumber;
    @BindView(R.id.et_sim)
    EditText etSimYanZheng;
    @BindView(R.id.rl_idcardinfo)
    RelativeLayout rlIDcardInfo;
    @BindView(R.id.iv_zm)
    ImageView ivZM;
    @BindView(R.id.iv_bm)
    ImageView ivBM;
    @BindView(R.id.iv_sc)
    ImageView ivSC;
    @BindView(R.id.iv_sl)
    ImageView ivSL;
    @BindView(R.id.tv_xmtext)
    TextView tvXMtext;
    @BindView(R.id.tv_username)
    TextView tvUserName;
    @BindView(R.id.txt_idcardnumber)
    TextView tvIDNumberText;
    @BindView(R.id.txt_idnumber)
    TextView tvIDNumber;
    @BindView(R.id.iv_headPhote)
    ImageView ivPhoto;
    @BindView(R.id.buka_submit_btn)
    Button ivSumbit;
    @BindView(R.id.rl_kaika_saoma)
    RelativeLayout rlSaoMa;
    @BindView(R.id.rl_sign)
    RelativeLayout rl_sign;
    @BindView(R.id.ll_handpic)
    LinearLayout llHandPic;
    @BindView(R.id.iv_handsign)
    ImageView ivHandSign;
    private String handSignUrlRep;


    private MyUsualyDialog dialog;
    Intent mInetent;
    private String bukaNumber;
    private String yanzhengSim;
    public static final int BUKA_READKAR_REQUEST = 9879;
    /**
     * 套餐组id  套餐id 号码id  ICCID id 证件号码 证件名称  联系方式
     */
    private String mPackageGroupID = null, mPhoneNumID = null,
            mPackageID = null, mICCID_ID = null, mIDCard_Num = null,
            mIDCard_Name = null, mContactPhone = null;

    private HashMap<String, String> mImgMap;
    String orderSn;
    String url;
    @BindView(R.id.buka_oper_title_tv)
    TextView mBukaOperTitleTv;
    @BindView(R.id.real_name_auth_title_tv)
    TextView mRealNameAuthTitleTv;
    @BindView(R.id.user_pic_upload_title_tv)
    TextView mUserPicUploadTitleTv;
    @BindView(R.id.user_sign_pic_title_tv)
    TextView mUserSignPciTitleTv;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buka);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initView();
        initData();
    }

    @Override
    public void setTheme() {

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    private void initView() {
        mBukaOperTitleTv.setTextSize(15);
        mRealNameAuthTitleTv.setTextSize(15);
        mUserPicUploadTitleTv.setTextSize(15);
        mUserSignPciTitleTv.setTextSize(15);
        txtPagetitle.setText("补卡");
        ivLin.setVisibility(View.GONE);
        llTakePic.setVisibility(View.GONE);


        mImgMap = new HashMap<>();
        dialog = new MyUsualyDialog(this, R.layout.wait_item);
    }

    private void initData() {
    }

    //, R.id.btn_simcar
    @OnClick({R.id.rl_goback, R.id.rl_saomiao, R.id.rl_loadtake
            , R.id.iv_querynumber, R.id.buka_submit_btn, R.id.rl_kaika_saoma, R.id.rl_sign
    })
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.rl_goback:
                finish();//返回
                break;
            case R.id.rl_saomiao:
                //扫身份证信息
                mInetent = new Intent(this, SearchBlueActivity.class);
                mInetent.putExtra("isTest", "0");
                startActivityForResult(mInetent, BUKA_READKAR_REQUEST);
                break;
            case R.id.rl_loadtake:
                //照片上传
                mInetent = new Intent(this, KaikaUploadPicActivity.class);
                startActivityForResult(mInetent, KaikaUploadPicActivity.KAIKA_UP_USER_IMG_REQUEST);
                break;
            case R.id.iv_querynumber:
                //验证补卡号码
                bukaNumber = etbuKaNumber.getText().toString().trim();

                //String telRegex2 = "^\\d{11}$";
                if (!TextUtils.isEmpty(bukaNumber)) {
                    if (bukaNumber.length() == 11) {
                        dialog.show();
                        App.getApp().getHttpTools().getBuKaPhoneInfo(bukaNumber, new RequestCallBack<String>() {
                            @Override
                            public void onSuccess(String result) {
                                if (activityIsDestory()) {
                                    return;
                                }
                                try {
                                    dialog.dismiss();
                                    JSONObject jsonObject = new JSONObject(result);
                                    if ("1".equals(jsonObject.optString("status"))) {
                                        showToast("" + jsonObject.optString("info"));
                                    } else {
                                        showToast("" + jsonObject.optString("info"));
                                    }
                                } catch (Exception e) {
                                }
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                if (activityIsDestory()) {
                                    return;
                                }
                                dialog.dismiss();
                                showToast(getResources().getString(R.string.connect_sever_error_toast));
                            }

                            @Override
                            public void onCancelled(Callback.CancelledException cex) {
                            }

                            @Override
                            public void onFinished() {
                            }
                        });
                    } else {
                        showToast("请输入11位手机号码");
                    }
                } else {
                    showToast("请输入您的补卡号码");
                }
                break;
            case R.id.rl_kaika_saoma:
                //扫码
                mInetent = new Intent(BukaActivity.this, TiaoXingMaActivity.class);
                startActivityForResult(mInetent, TiaoXingMaActivity.REQ_CODE);
                break;

            case R.id.rl_sign:
                //手写签名
                mInetent = new Intent(this, HengXiangSign.class);
                mInetent.putExtra("position", "512");
                startActivityForResult(mInetent, 1559);
                break;

            case R.id.buka_submit_btn:
                yanzhengSim = etSimYanZheng.getText().toString().trim();
                String imgJson = JSON.toJSONString(mImgMap);
                bukaNumber = etbuKaNumber.getText().toString().trim();
                if (TextUtils.isEmpty(bukaNumber)) {
                    showToast("请输入您的补卡号码");
                    return;
                }
                if (bukaNumber.length() != 11) {
                    showToast("请输入11位手机号码");
                    return;
                }
                if (TextUtils.isEmpty(yanzhengSim)) {
                    showToast("请输入您的SIM卡号");
                    return;
                }
                if (TextUtils.isEmpty(mIDCard_Num)) {
                    showToast("请先扫描身份证件");
                    return;
                }

                if (TextUtils.isEmpty(handSignUrlRep)) {
                    showToast("请上传签名");
                    return;
                }
                ivSumbit.setEnabled(false);
                dialog.show();
                App.getApp().getHttpTools().submitBuKaOrder(bukaNumber, yanzhengSim, mIDCard_Num, imgJson, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        if (activityIsDestory()) {
                            return;
                        }
                        etSimYanZheng.setText(null);
                        etbuKaNumber.setText(null);
                        mIDCard_Num = null;
                        try {
                            BuKaMoneyModel buKaMoneyModel = JSON.parseObject(result, BuKaMoneyModel.class);
                            if (buKaMoneyModel != null) {
                                if (buKaMoneyModel.getStatus() == 1) {
                                    orderSn = buKaMoneyModel.getData().getOrder_sn();
                                    //url = "/index.php/DxApp/Order/buka_info.html";
                                    url = buKaMoneyModel.getData().getInfo();

                                    if (buKaMoneyModel.getData().getIs_duibi() == 1) {
                                        //对比接口
                                        verifyOrder();
                                    } else if (buKaMoneyModel.getData().getIs_duibi() == 0) {
                                        /**跳到详情*/
                                        bukaKaiHui(orderSn, url);
                                    }
                                } else {
                                    if (dialog != null) {
                                        dialog.dismiss();
                                    }
                                    ivSumbit.setEnabled(true);
                                    showErrorToast( buKaMoneyModel.getInfo());
                                }
                            } else {
                                ivSumbit.setEnabled(true);
                                if (dialog != null) {
                                    dialog.dismiss();
                                }
                                showToast("数据出错,请重试");
                            }
                        } catch (Exception ex) {
                            ivSumbit.setEnabled(false);
                            if (dialog != null) {
                                dialog.dismiss();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        if (activityIsDestory()) {
                            return;
                        }
                        ivSumbit.setEnabled(true);
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        showToast("网络异常,请检查网络并重试");
                    }

                    @Override
                    public void onCancelled(Callback.CancelledException cex) {
                    }

                    @Override
                    public void onFinished() {
                    }
                });
                break;
            default:
                break;
        }
    }

    /**
     * 校验
     */
    private void verifyOrder() {
        App.getApp().getHttpTools().getBuKaDuiBi(orderSn, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                if (activityIsDestory()) {
                    return;
                }
                BuKaDuibiInfo duibimodel = JSON.parseObject(result, BuKaDuibiInfo.class);

                if (duibimodel.getStatus() == 1) {
                    if (duibimodel.getData().getIs_kaihu() == 0) {
                        //跳转详情页
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        mInetent.setClass(BukaActivity.this, DingDanDetailsActivity.class);
                        mInetent.putExtra("order_sn", orderSn);
                        mInetent.putExtra("orderInfo", url);
                        mInetent.putExtra("title", "补卡详情");
                        startActivity(mInetent);
                        finish();
                    } else if (duibimodel.getData().getIs_kaihu() == 1) {
                        //开户
                        bukaKaiHui(orderSn, url);
                    }
                } else {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    mInetent.setClass(BukaActivity.this, DingDanDetailsActivity.class);
                    mInetent.putExtra("order_sn", orderSn);
                    mInetent.putExtra("orderInfo", url);
                    mInetent.putExtra("title", "补卡详情");
                    startActivity(mInetent);
                    showToast(duibimodel.getInfo());
                    finish();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (activityIsDestory()) {
                    return;
                }
                if (dialog != null) {
                    dialog.dismiss();
                }

                //showToast("网络异常,请检查网络并重试");
                showToast("人脸对比超时，请重试");
                mInetent.setClass(BukaActivity.this, DingDanDetailsActivity.class);
                mInetent.putExtra("order_sn", orderSn);
                mInetent.putExtra("orderInfo", url);
                mInetent.putExtra("title", "补卡详情");
                startActivity(mInetent);
                finish();
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    /*----------------上传身份证图片----------------------*/
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void getUpLoadPicEventBus(Map<String, File> msg) {

        File zhengMianFile = msg.get("zhengMianFile");
        File beiMianFile = msg.get("beiMianFile");
        File shouChiFile = msg.get("shouChiFile");
        llTakePic.setVisibility(View.VISIBLE);
        ivSL.setVisibility(View.GONE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case KaikaUploadPicActivity.KAIKA_UP_USER_IMG_REQUEST:
                    llTakePic.setVisibility(View.VISIBLE);
                    ivSL.setVisibility(View.GONE);
                    Glide.with(getActivity()).load(data.getStringExtra(KaikaUploadPicActivity.ZHENGMIAN_URL_REP)).into(ivZM);
                    Glide.with(getActivity()).load(data.getStringExtra(KaikaUploadPicActivity.BEIMIAN_URL_REP)).into(ivBM);
                    Glide.with(getActivity()).load(data.getStringExtra(KaikaUploadPicActivity.SHOUCHI_URL_REP)).into(ivSC);


                    mImgMap.put("handheld_img_info", data.getStringExtra(KaikaUploadPicActivity.SHOUCHI_URL));
                    mImgMap.put("card_img_1_info", data.getStringExtra(KaikaUploadPicActivity.ZHENGMIAN_URL));
                    mImgMap.put("card_img_2_info", data.getStringExtra(KaikaUploadPicActivity.BEIMIAN_URL));

                    break;
                case BUKA_READKAR_REQUEST:
                    //身份证照片上传  //扫身份证  结果
                    Bundle bundle = data.getExtras();
                    rlIDcardInfo.setVisibility(View.VISIBLE);
                    if (bundle != null) {
                        mIDCard_Num = bundle.getString("id_num");

                        mIDCard_Name = bundle.getString("name");

                        byte[] photo = bundle.getByteArray("photo");
                        String filePhoto = bundle.getString("filePhoto");
                        Bitmap bitmap = BitmapFactory.decodeByteArray(photo, 0, photo.length);
                        String photoHeard = bundle.getString("photoHeard");

                        tvXMtext.setVisibility(View.VISIBLE);
                        tvUserName.setText(mIDCard_Name);
                        tvIDNumberText.setVisibility(View.VISIBLE);
                        tvIDNumber.setText(mIDCard_Num);
                        ivPhoto.setImageBitmap(bitmap);
                    }
                    break;
                case TiaoXingMaActivity.REQ_CODE:
                    String iccid = data.getStringExtra(TiaoXingMaActivity.INTENT_ICCID);
                    if (TextUtils.isEmpty(iccid)) {
                        return;
                    }
                    etSimYanZheng.setText(iccid);
                    yanzhengSim = iccid;
                    return;
                case 1559:
                    llHandPic.setVisibility(View.VISIBLE);
                    handSignUrlRep = data.getStringExtra(HengXiangSign.SIGN_IMG__URL);
                    Glide.with(getActivity()).load(data.getStringExtra(HengXiangSign.SIGN_IMG__URL_REP))
                            .into(ivHandSign);
                    mImgMap.put("card_img_4_info", data.getStringExtra(HengXiangSign.SIGN_IMG__URL));
                    break;
                default:
                    break;
            }
        }
    }


    private void bukaKaiHui(final String toorder, final String tourl) {
        // 跳到详情
        App.getApp().getHttpTools().getBuKaKaiHui(toorder, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {
            }

            @Override
            public void onFinished() {
                if (activityIsDestory()) {
                    return;
                }
                if (dialog != null) {
                    dialog.dismiss();
                }
                mInetent.setClass(BukaActivity.this, DingDanDetailsActivity.class);
                mInetent.putExtra("order_sn", toorder);
                mInetent.putExtra("orderInfo", tourl);
                mInetent.putExtra("title", "补卡详情");
                startActivity(mInetent);
                finish();
            }
        });
    }
}
